#!/usr/bin/env python
# -*- coding: UTF-8 -*-

from dbus.exceptions import IntrospectionParserException
from xml.parsers.expat import ExpatError, ParserCreate

#----------------------------------------------------------------------------#
class _Parser(object):
#----------------------------------------------------------------------------#
# Copyright (C) 2003, 2004, 2005, 2006 Red Hat Inc. <http://www.redhat.com/>
# Copyright (C) 2003 David Zeuthen
# Copyright (C) 2004 Rob Taylor
# Copyright (C) 2005, 2006 Collabora Ltd. <http://www.collabora.co.uk/>
# Copyright (C) 2007 John (J5) Palmieri
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use, copy,
# modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    __slots__ = ('map',
                 'in_iface',
                 'in_method',
                 'in_signal',
                 'in_property',
                 'property_access',
                 'in_sig',
                 'out_sig',
                 'node_level',
                 'in_signal')
    def __init__(self):
        self.map = {'child_nodes':[],'interfaces':{}}
        self.in_iface = ''
        self.in_method = ''
        self.in_signal = ''
        self.in_property = ''
        self.property_access = ''
        self.in_sig = []
        self.out_sig = []
        self.node_level = 0

    def parse(self, data):
        parser = ParserCreate('UTF-8', ' ')
        parser.buffer_text = True
        parser.StartElementHandler = self.StartElementHandler
        parser.EndElementHandler = self.EndElementHandler
        parser.Parse(data)
        return self.map

    def StartElementHandler(self, name, attributes):
        if name == 'node':
            self.node_level += 1
            if self.node_level == 2:
                self.map['child_nodes'].append(attributes['name'])
        elif not self.in_iface:
            if (not self.in_method and name == 'interface'):
                self.in_iface = attributes['name']
        else:
            if (not self.in_method and name == 'method'):
                self.in_method = attributes['name']
            elif (self.in_method and name == 'arg'):
                arg_type = attributes['type']
                arg_name = attributes.get('name', None)
                if attributes.get('direction', 'in') == 'in':
                    self.in_sig.append({'name': arg_name, 'type': arg_type})
                if attributes.get('direction', 'out') == 'out':
                    self.out_sig.append({'name': arg_name, 'type': arg_type})
            elif (not self.in_signal and name == 'signal'):
                self.in_signal = attributes['name']
            elif (self.in_signal and name == 'arg'):
                arg_type = attributes['type']
                arg_name = attributes.get('name', None)

                if attributes.get('direction', 'in') == 'in':
                    self.in_sig.append({'name': arg_name, 'type': arg_type})
            elif (not self.in_property and name == 'property'):
                prop_type = attributes['type']
                prop_name = attributes['name']

                self.in_property = prop_name
                self.in_sig.append({'name': prop_name, 'type': prop_type})
                self.property_access = attributes['access']


    def EndElementHandler(self, name):
        if name == 'node':
            self.node_level -= 1
        elif self.in_iface:
            if (not self.in_method and name == 'interface'):
                self.in_iface = ''
            elif (self.in_method and name == 'method'):
                if not self.map['interfaces'].has_key(self.in_iface):
                    self.map['interfaces'][self.in_iface]={'methods':{}, 'signals':{}, 'properties':{}}

                if self.map['interfaces'][self.in_iface]['methods'].has_key(self.in_method):
                    print "ERROR: Some clever service is trying to be cute and has the same method name in the same interface"
                else:
                    self.map['interfaces'][self.in_iface]['methods'][self.in_method] = (self.in_sig, self.out_sig)

                self.in_method = ''
                self.in_sig = []
                self.out_sig = []
            elif (self.in_signal and name == 'signal'):
                if not self.map['interfaces'].has_key(self.in_iface):
                    self.map['interfaces'][self.in_iface]={'methods':{}, 'signals':{}, 'properties':{}}

                if self.map['interfaces'][self.in_iface]['signals'].has_key(self.in_signal):
                    print "ERROR: Some clever service is trying to be cute and has the same signal name in the same interface"
                else:
                    self.map['interfaces'][self.in_iface]['signals'][self.in_signal] = (self.in_sig,)

                self.in_signal = ''
                self.in_sig = []
                self.out_sig = []
            elif (self.in_property and name == 'property'):
                if not self.map['interfaces'].has_key(self.in_iface):
                    self.map['interfaces'][self.in_iface]={'methods':{}, 'signals':{}, 'properties':{}}

                if self.map['interfaces'][self.in_iface]['properties'].has_key(self.in_property):
                    print "ERROR: Some clever service is trying to be cute and has the same property name in the same interface"
                else:
                    self.map['interfaces'][self.in_iface]['properties'][self.in_property] = (self.in_sig, self.property_access)

                self.in_property = ''
                self.in_sig = []
                self.out_sig = []
                self.property_access = ''

#----------------------------------------------------------------------------#
def process_introspection_data(data):
#----------------------------------------------------------------------------#
    """Return a structure mapping all of the elements from the introspect data
       to python types TODO: document this structure

    :Parameters:
        `data` : str
            The introspection XML. Must be an 8-bit string of UTF-8.
    """
    try:
        return _Parser().parse(data)
    except Exception, e:
        raise IntrospectionParserException('%s: %s' % (e.__class__, e))



    

import gobject
import dbus, dbus.mainloop.glib
from dbus import SystemBus, Interface
from dbus.exceptions import DBusException
#from loggers import loggers
#logger = loggers('sms-middleware', 'sms-middleware.log')
#global logger
    
#----------------------------------------------------------------------------#
class DBusObject(object):
#----------------------------------------------------------------------------#
    def __init__(self, logger):
        self.logger = logger
        self.objects = {}
        self.gui_interfaces = {}
        self.interfaces = {}
        self.methods = {}
        self.p_factory = None # plugin factory object
        
    def tryGetProxy(self, busname, objname):
        object = None
        try:
            object = self.objects["%s:%s" % (busname, objname)]
        except KeyError:
            try:
                object = self.bus.get_object(busname, objname)
            except DBusException, e:
                self.logger.warning("could not create proxy for %s:%s" % (busname, objname ))
            else:
                self.objects["%s:%s" % (busname, objname)] = object
        return object

    def initialize(self):
        try:
            dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
            self.mainloop = gobject.MainLoop()
            self.logger.info("trying to get bus...")
            try:
                self.bus = dbus.SystemBus()
            except Exception, e:
                self.logger.exception("can't connect to dbus: %s" % e)
            self.logger.info("ok")

            #self.bus = SystemBus( mainloop=e_dbus.DBusEcoreMainLoop() )
        except DBusException, e:
            self.logger.exception("could not connect to dbus_object system bus: %s" % e)
            return False

    def build_ifaces(self):
        # Phone
        self.gsm_device_obj = self.tryGetProxy( 'org.freesmartphone.ogsmd', '/org/freesmartphone/GSM/Device' )
        if self.gsm_device_obj == None:
            self.logger.error( "could not get proxy from /org/freesmartphone/GSM/Device -- is the framework daemon started?" )
            return False
        self.gsm_sim_iface = Interface(self.gsm_device_obj, 'org.freesmartphone.GSM.SIM')
        self.gsm_sim_iface.connect_to_signal( "IncomingMessage", self.cbNewMessage )
            
        fw_obj = self.tryGetProxy( 'org.freesmartphone.frameworkd', '/org/freesmartphone/Framework' )
        if fw_obj is None:
            self.logger.error( "could not connect to org.freesmartphone.frameworkd -- is the framework daemon started?" )
            return False
        else:
            self.fw = Interface( fw_obj, "org.freesmartphone.Objects" )
                
        self.list_interfaces('org.freesmartphone.frameworkd', '/org/freesmartphone/GSM/Device')
        self.list_interfaces('org.freesmartphone.ousaged', '/org/freesmartphone/Usage')
        self.list_interfaces('org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
        self.list_interfaces('org.freesmartphone.odeviced', '/org/freesmartphone/Device')
        for iface in ('org.freesmartphone.Device.PowerSupply', 'org.freesmartphone.Device.IdleNotifier', 'org.freesmartphone.Device.Display'):
            obj_list = self.fw.ListObjectsByInterface('org.freesmartphone.Device.PowerSupply')
            if obj_list:
                self.list_interfaces('org.freesmartphone.odeviced', obj_list[0])

        self.logger.info('Registered %s interfaces' % (len(self.interfaces)))
        return True

    def generate_gui_ifaces(self):
        fw_obj = self.tryGetProxy( 'org.freesmartphone.frameworkd', '/org/freesmartphone/Framework' )
        if fw_obj is None:
            self.logger.error( "could not connect to org.freesmartphone.frameworkd -- is the framework daemon started?" )
            return False
        else:
            self.fw = Interface( fw_obj, "org.freesmartphone.Objects" )
                
        self.list_interfaces('org.freesmartphone.frameworkd', '/org/freesmartphone/GSM/Device')
        self.list_interfaces('org.freesmartphone.ousaged', '/org/freesmartphone/Usage')
        self.list_interfaces('org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
        self.list_interfaces('org.freesmartphone.odeviced', '/org/freesmartphone/Device')
        for iface in ('org.freesmartphone.Device.PowerSupply', 'org.freesmartphone.Device.IdleNotifier', 'org.freesmartphone.Device.Display'):
            obj_list = self.fw.ListObjectsByInterface(iface)
            if obj_list:
                self.list_interfaces('org.freesmartphone.odeviced', obj_list[0])

        return self.gui_interfaces
        
    def list_interfaces(self, busname, objname):
        obj = self.tryGetProxy(busname, objname)
        if obj is not None:
            data = process_introspection_data(obj.Introspect())
            for name, interface in data["interfaces"].iteritems():
                self.interfaces[name] = Interface(obj, name)
                self.methods[name] = [method_name for method_name in interface['methods'].keys()]
                method_list = []
                for method_name in interface["methods"].keys():
                    #print "[METHOD] %s.%s%s" % (name, method_name, self._signature(interface["methods"][method_name]))
                    method_list.append({'method':method_name, 
                                        'signature':self._signature(interface["methods"][method_name])
                                        })
                self.gui_interfaces[name] = {'interface':self.interfaces[name],
                                             'method_list':method_list,}
                
    def _signature(self, parameters):
        sig_str = "("
        for p in parameters[0]:
            sig_str += "%s:%s, " % (p["type"], p["name"])
        if len(sig_str) == 1:
            return "()"
        else:
            return sig_str[:-2] + ")"

    """            
    def list_methods(self, busname, objname):
        obj = self.tryGetProxy(busname, objname)
        if obj is not None:
            data = process_introspection_data(obj.Introspect())
            for name, interface in data["interfaces"].iteritems():
                self.methods[name] = [method_name for method_name in interface['methods'].keys()]
                for method_name in interface["methods"].keys():
                    print "[METHOD] %s.%s%s" % (name, method_name, self._signature(interface["methods"][method_name]))
    """
    
    def run(self):
        self.mainloop.run()
        
    def quit(self):
        self.mainloop.quit()

    ############################################################################
    def cbNewMessage(self, index):
        self.logger.info('There is a new message int=%s' % (index))
        
        self.gsm_sim_iface.RetrieveMessagebook(
            "unread",
            reply_handler=self.cbMessagebookReply,
            error_handler=lambda e: self.logger.error("error while retrieving messagebook %s" % (e))
        )
        
        """
        self.gsm_sim_iface.RetrieveMessage(
            index,
            reply_handler=self.cbMessagebookReply,
            error_handler=lambda e: self.logger.error("error while retrieving messagebook %s" % (e))
        )
        """

    def cbMessagebookReply(self, result):
        if type(result) != list:
            result = [result]
        for sms in result:
            self.logger.info("retrieved messagebook: \n\tindex=%s, \n\tstatus=%s, \n\tsender=%s, \n\tbody=%s" % (sms[0], sms[1], sms[2], sms[3]))
            self.p_factory.proceed(index=sms[0],
                                   status=sms[1],
                                   sim_number=sms[2],
                                   text=sms[3],
                                   interfaces=self.interfaces,)

    